package com.weixin.service;

import java.util.Map;

import org.apache.log4j.Logger;

import com.weixin.model.AppConfig;
import com.weixin.model.AppMenu;
import com.weixin.model.AppUser;
import com.wxwyapp.controller.BusinessPropertyController;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;


/*******************************************
 * 作用描述：网欣物业对外公众服务后台服务层
 *******************************************
 * @author LRC
 * @createDate 2015-9-20
 * @version v1.0 
 * @updateRecord 格式：时间，作者，修改说明
 *******************************************
 * 
 */
public class WxWyPublicService {
	
	public static Logger log = Logger.getLogger(WxWyPublicService.class);
	
	/**
	 * 公众号映射的内部请求路径
	 */
	public static final String MAPPING_URL = "/weixin/wxwypub";

	// 微信配置存储组件
	protected static WxMpInMemoryConfigStorage wxMpConfigStorage;
	// 微信服务组件
	protected static WxMpService wxMpService;
	// 微信请求路由控制器
	protected static WxMpMessageRouter wxMpMessageRouter;
	// 微信组件初始化标识
	protected static Boolean wxBassIsInit = false;
	
	// 对应数据库中配置项的ID
	protected static Object appcfgId;
	
	public static WxMpInMemoryConfigStorage getWxMpInMemoryConfigStorage(){
		return wxMpConfigStorage;
	}
	public static WxMpService getWxMpService(){
		return wxMpService;
	}
	public static WxMpMessageRouter getWxMpMessageRouter(){
		return wxMpMessageRouter;
	}
	public static boolean checkSignature(String timestamp, String  nonce, String signature){
		
		return wxMpService.checkSignature(timestamp, nonce, signature);
		
	}
	
	/**
	 * 功能描述：初始化配置
	 * 
	 * @throws Exception
	 * @createDate 2015-9-21 by LRC
	 * @updateRecord 格式：时间，作者，修改说明
	 ** 
	 * 
	 */
	public synchronized static void initWxConfig() throws Exception {
		if (wxBassIsInit)
			return;
		System.out.println(" WxWyPubContoller initWxConfig() start ... ");

		// 从数据库中获取配置数据
		AppConfig config = AppConfig.dao.findFirstByMappingURL(MAPPING_URL);
		if (config == null) {
			wxBassIsInit = true;
			throw new Exception(" no appConfig found . mappingUrl=" + MAPPING_URL);
		}
		/**
		 * 微信公众号连接配置文件
		 */
		String appId = config.get("appId");
		String appsecret = config.get("appsecret");
		String token = config.get("token");
		String aesKey = config.get("aesKey");

		wxMpConfigStorage = new WxMpInMemoryConfigStorage();

		// 设置微信公众号的appid
		wxMpConfigStorage.setAppId(appId);

		// 设置微信公众号的app corpSecret
		wxMpConfigStorage.setSecret(appsecret);

		// 设置微信公众号的token
		wxMpConfigStorage.setToken(token);

		// 设置微信公众号的EncodingAESKey 测试账号不需要
		if ("F".equals(config.get("testAccount"))) {
			wxMpConfigStorage.setAesKey(aesKey);
		}

		wxMpService = new WxMpServiceImpl();

		wxMpService.setWxMpConfigStorage(wxMpConfigStorage);

		// 设置菜单
		appcfgId = config.getInt("id");
		AppMenu.initMenu(wxMpService,appcfgId);

		// 注册路由
		wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
		registerWxMpMessageRouter(wxMpMessageRouter);
		

		wxBassIsInit = true;
		
		System.out.println(" WxWyPubContoller initWxConfig() completed ");
	}
	
	/**
	 * 注册服务路由
	 * 功能描述：
	 * @createDate 2015-9-21 by LRC 
	 * @updateRecord 格式：时间，作者，修改说明
	 **
	 *
	 */
	public static void registerWxMpMessageRouter(WxMpMessageRouter _wxMpMessageRouter){
		/**
		 * 注册消息处理器注册
		 */
		WxMpMessageHandler handler = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
				
				WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content("测试加密消息").fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName()).build();
				
				return m;
			}
		};
		// 拦截内容为"哈哈"的消息
		_wxMpMessageRouter.rule().async(false).content("哈哈").handler(handler).end();
	}
	
	/**
	 * 验证url授权验证请求重定向页面中的state是否合法
	 * @updateTeim 2015年9月27日下午11:26:58
	 * @description 
	 * @return
	 */
	public static boolean validateState(String state){
		if(AppMenu.STATE.equals(state)){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 功能描述：根据微信授权code获取微信bind的用户信息
	 * @createDate 2015年10月10日 by LRC
	 * @param code
	 * @return 
	 * @updateRecord 格式：时间，作者，修改说明
	 **
	 * 
	 */
	public static AppUser getAppUserByCode(String code){
		try {
			//根据code微信认证令牌
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
			//获取用户信息
			WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
			String openId =  wxMpUser.getOpenId();
			AppUser appUser = AppUser.dao.getBindUserByOpenId(openId);
			if(appUser==null){
				appUser = new AppUser();
				appUser.set("openId", openId);
				appUser.set("nickname", wxMpUser.getNickname());
				appUser.set("bindStatus", 0);//未绑定
				//后台保存数据
				appUser.save();
			}
			return appUser;
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("用户微信用户id失败，code="+code);
			return null;
		}
	}

	public static WxMpXmlOutMessage route(WxMpXmlMessage inMessage) {
		
		return wxMpMessageRouter.route(inMessage);
	}
}
